package priv.hxm.serve;


import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.apache.log4j.Logger;
import priv.hxm.serve.clientMsgHandler.ClientMsgHandler;
import priv.hxm.serve.clientMsgHandler.HandleMsg;
import priv.mill.net.MyHttp;
import priv.mill.net.UrlType;


public class MyServerHandler extends ChannelHandlerAdapter {
	private static Logger logger = Logger.getLogger(MyServerHandler.class);

	/**
	 * 客户端的正常退出会抛出异常，我们不需要进行显示
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {

		SessionContext.remove(ctx.channel());
		cause.printStackTrace();

	}

	/**
	 * 客户端提交请求，服务器提供响应
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		MyHttp m = (MyHttp) msg;
		// // 如果是登陆信息
		// if (m.getData() instanceof ChinaUser &&
		// m.getMyUrl().equals(Urls.Login))
		// SessionContext.put(ctx.channel(), (ChinaUser) msg);

		/*
		 * 处理客户端发来的消息
		 */

		ClientMsgHandler clientMsgHandler = HandleMsg.getHandleMsg()// 获取消息处理实例
				.getClientMsgHandler(m);

		String result = clientMsgHandler.doIt(m);

		/*
		 * 返回给客户端的消息
		 */
		MyHttp myHttp = new MyHttp();
		myHttp.setData(result);
		myHttp.setType(UrlType.NALMORE);
		ctx.writeAndFlush(myHttp);
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		super.handlerRemoved(ctx);
	}

}
